<!-- 根据商品属性渲染出SKU组件 -->
<template>
  <div class="goods-sku">
    <dl v-for="(item, index) in goods.specs" :key="index">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="(val, i2) in item.values" :key="i2">
          <img
            :class="{ selected: val.selected, disabled: val.disabled }"
            @click="clickSpecs(item, val)"
            v-if="val.picture"
            :src="val.picture"
            :title="val.name"
          />
          <span
            :class="{ selected: val.selected, disabled: val.disabled }"
            @click="clickSpecs(item, val)"
            :title="val.desc"
            v-else
          >{{ val.name }}</span>
        </template>
      </dd>
    </dl>
  </div>
</template>

<script>
import getPowerSet from "@/vender/power-set"

/**
 * 获取可以选择的对象
 * @param {Array} skus 
 * @returns {key:'&',value: id}
 */
const getPathMap = (skus) => {
  const pathMap = {}
  skus.forEach(sku => {
    // 1.过滤出有效的sku
    if (sku.inventory) {
      // 2. 得到sku属性值数组
      const specs = sku.specs.map(spec => spec.valueName)
      // 3. 得到sku属性值数组的子集
      const powerSet = getPowerSet(specs)
      // 4. 设置给路径字典对象 - 存放id
      powerSet.forEach(set => {
        const key = set.join('&')
        if (pathMap[key]) {
          pathMap[key].push(sku.id)
        } else {
          pathMap[key] = [sku.id]
        }
      })
    }
  })
  return pathMap
}

// 得到当前规格下的所有选中状态
const getSelectedArr = (specs) => {
  // 一个参数就是一个规格得选中状态
  let selectedArr = []
  specs.forEach(item => {
    // 约定选中状态为 selected
    const selectedItem = item.values.find(val => val.selected)
    // 有的行可能未选中, 未选中设置为 undefined
    selectedArr.push(selectedItem ? selectedItem.name : undefined)
  })
  return selectedArr
}

// 检测按钮是否应该为禁用状态
const testDisabledStatus = (specs, pathMap) => {
  specs.forEach((spec, i) => {
    // 因为每次都会替换其中选中得元素, 所以需要每次都需要重新生成
    let selectedArr = getSelectedArr(specs)
    spec.values.forEach(val => {
      // 已经选中的按钮不用判断
      if (val.name === selectedArr[i]) return false
      // 未选中的替换对应的值,== 会导致记录最后一个为选中状态,
      selectedArr[i] = val.name
      // 过滤无效值得到key
      const key = selectedArr.filter(v => v).join('&')
      // 设置禁用状态
      val.disabled = !pathMap[key]
    })
  })

}

// 初始化按钮选中状态
const initSelectedStatus = (goods, skuId) => {
  const selectedSku = goods.skus.find(sku => sku.id === skuId)
  if (selectedSku) {
    goods.specs.forEach((spec, i) => {
      const value = selectedSku.specs[i].valueName
      spec.values.forEach(item => {
        item.selected = value == item.name
      })
    })
  }
}

export default {
  name: 'GoodsSku',
  props: {
    goods: {
      type: Object,
      default: () => ({})
    },
    skuId: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    // 获取可以选择对象得集合图
    const pathMap = getPathMap(props.goods.skus)
    initSelectedStatus(props.goods, props.skuId)
    // 组件初始化的时候更新禁用状态
    testDisabledStatus(props.goods.specs, pathMap)

    // 选择商品规格
    const clickSpecs = (item, val) => {
      // 如果是禁用状态不作为
      if (val.disabled) return false

      if (val.selected)
        val.selected = false
      else {
        item.values.forEach(e => e.selected = false)
        val.selected = true
      }

      // 每次点击都要检测那些选项应该禁用
      testDisabledStatus(props.goods.specs, pathMap)

      // 触发change事件将sku数据传递出去
      const selectedArr = getSelectedArr(props.goods.specs).filter(e => e)
      if (selectedArr.length === props.goods.specs.length) {
        // pathMap存放了id
        const skuIds = pathMap[selectedArr.join('&')]
        const sku = props.goods.skus.find(e => e.id == skuIds[0])
        // 每个商品得价格都可能是不同得， 需要实时更新
        emit('change', {
          skuId: sku.id,
          price: sku.price,
          oldPrice: sku.oldPrice,
          inventory: sku.inventory,
          specsText: sku.specs.reduce((p, n) => `${p} ${n.name}：${n.valueName}`, '').trim()
        })
      } else {
      }
    }
    return {
      clickSpecs
    }
  },

}

</script>



<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      > img {
        width: 50px;
        height: 50px;
        margin: 5px 0;

        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        margin: 5px 0;
        .sku-state-mixin ();
      }
    }
  }
}
</style>